package cn.hiapi.shopkeeper.service.shopkeeper;

import cn.hiapi.basic.jpa.pageable.QueryWrapper;
import cn.hiapi.basic.service.AbsBasicService;
import cn.hiapi.shopkeeper.entity.shopkeeper.ShopUser;
import cn.hiapi.shopkeeper.jpa.shopkeeper.ShopUserJpa;
import org.springframework.stereotype.Service;

/**
 * @author AdinZ
 * @date 2023/1/31 23:37
 */
@Service
public class ShopUserService extends AbsBasicService<ShopUserJpa, ShopUser, Long> {


    private final String KEY = "CORE:SHOPKEEPER:SHOP_USER";

    private String getKey(long shopId, long uid) {
        return new StringBuffer().append(shopId).append("-").append(uid).toString();
    }


    /**
     * 创建用户
     *
     * @param shopId
     * @param uid
     */
    public void createUser(long shopId, long uid, long aid) {
        Object o = this.redisService.get(KEY, getKey(shopId, uid));
        if (o != null) return;
        ShopUser user = new ShopUser();
        user.setShopId(shopId);
        user.setUid(uid);
        user.setAid(aid);
        this.save(user);
        this.redisService.set(KEY, getKey(shopId, uid), user);
    }

    /**
     * 本活动总新增用户
     *
     * @param aid
     * @return
     */
    public long totalByAid(long aid) {
        return this.count(new QueryWrapper().eq("aid", aid));
    }

    /**
     * 今日新增用户
     *
     * @param aid
     * @param day
     * @return
     */
    public long totalByAid(long aid, String day) {
        return this.count(new QueryWrapper().eq("aid", aid).eq("day", day));
    }

    /**
     * 统计时间范围内的新增用户数
     *
     * @param shopId
     * @param startTime
     * @param endTime
     * @return
     */
    public long totalCount(long shopId, long startTime, long endTime) {
        return this.count(new QueryWrapper().eq("shopId", shopId).between("created", startTime, endTime));
    }
}
